#import "ToDoOrderByView.h"

@implementation ToDoOrderByView

- (id)initWithFrame:(struct CGRect)frame
{
	self = [super initWithFrame:frame];
	
	toDoManager = [ToDoManager sharedToDoManager];
	td = [MobileToDoListApplication sharedInstance];
	
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	table = [[UIPreferencesTable alloc] initWithFrame:CGRectMake(0.0f, 45.0f, 320.0f, 420.0f)];
	[table setDataSource:self];
	[table setDelegate:self];
	[table reloadData];
	
	navBar = [[UINavigationBar alloc] init];
	[navBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 45.0f)];
	[navBar showButtonsWithLeftTitle:@"back" rightTitle:nil leftBack:YES];
	[navBar setDelegate:self];
	[navBar enableAnimation];
	
	[self addSubview:navBar];
	[self addSubview:table];
	
	return self;
}

- (void)reloadTableData
{
	[table reloadData];
}

#pragma mark ----------Delegate Methods-----------

- (void)navigationBar:(UINavigationBar*)bar buttonClicked:(int)button
{
	// save data
	// Stupid BugFix...
	if([table selectedRow] <= 100000 && [table selectedRow] > 0) {
		[toDoManager setPref:@"orderBy" withValue:[[table cellAtRow:[table selectedRow] column:0] title]];
		[toDoManager writePreferences];
	}
	
	
	[table selectRow: 0 byExtendingSelection: NO withFade: NO];
	[td showToDoPreferencesWithTransition:2];
}

- (void)tableRowSelected:(NSNotification *)notification
{
	int i;
	for(i=0;i <= 4; i++) {
		[[table cellAtRow:i column:0] setChecked:NO];
	}
	[[table cellAtRow:[table selectedRow] column:0] setChecked:YES];
}

#pragma mark ----------Datasource Methods-----------

- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table
{
	return 1;
}

- (int)preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group
{
	return 4;
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForGroup:(int)group
{
	UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
	
	return [cell autorelease];
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group
{
	
	UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
	
	switch(row) {
		case 0:
			[cell setTitle:@"Due Date"];
			break;
		case 1:
			[cell setTitle:@"Priority"];
			break;
		case 2:
			[cell setTitle:@"Alphabetic"];
			break;
		case 3:
			[cell setTitle:@"Creation Date"];
			break;
	}
	[cell setChecked:NO];
	if([[cell title] isEqualToString:[toDoManager getPref:@"orderBy"]]) {
		[cell setChecked:YES];
	}
	return [cell autorelease];
}

@end